#__Author__  = white
import socket
import os,hashlib,json,sys,time,pickle,re
from FTP_client.conf import settings
from login import login
import global_manage

class FTP_CLIENT(object):
    def __init__(self):
        self.client = socket.socket()

    def help(self):
        msg = '''help:
        ls
        pwd
        put filename
        get filename
        cd ../..
        '''
        print(msg)
    def connect(self,IP,PORT):
        self.client.connect((IP,PORT))
        print("connect IP:%s PORT:%s success"%(IP,PORT))

    @login #初始化路径变量，也在login装饰器中实现
    def interactive(self):
        while True:
            cmd = input("ftp>> ")
            if cmd == "" : continue
            cmd_str = cmd.split()[0]
            if hasattr(self,'cmd_%s'%cmd_str):
                func = getattr(self,'cmd_%s'%cmd_str)
                func(cmd)
            else:
                self.help()
        self.client.close()



    def cmd_put(self,*args):
        #判断args的参数有几个，只取前两个。

        cmd_split = args[0].split()
        print(cmd_split)
        filename = cmd_split[1]
        print(filename)
        if os.path.isfile(filename):
            m = hashlib.md5()
            #fileaddr服务器端操作的路径信息，存储到公共变量，初始默认值，cd后发生变化。
            fileaddr = global_manage.get_value('current_path')
            file_size = os.stat(filename).st_size
            filename_simple = re.findall(r'[^//:*?"<>|\r\n]+$',filename)[0] #不含路径的文件名字
            print(filename,filename_simple)

            msg = {
                "action":"put",
                "filesize":file_size,
                "filename":filename_simple,
                "fileaddr":fileaddr
            }
            self.client.send(json.dumps(msg).encode("utf-8"))
            print("send%s"%json.dumps(msg))
            server_response = self.client.recv(1024)
            print("server_response:",server_response)
            f = open(filename, 'rb')
            print('filename',filename)

            for line in f:
                m.update(line)
                self.client.send(line)
            #self.client.send(m.hexdigest().encode("utf-8"))
            f.close()

        else:
            print("filename %s not exists"%filename)

    def cmd_get(self,*args):
        pass

    def cmd_ls(self,*args):
        fileaddr = global_manage.get_value('current_path')
        msg = {
            "fileaddr":fileaddr,
            "action":"ls"
        }
        self.client.send(json.dumps(msg).encode("utf-8"))
        print("send %s" % json.dumps(msg))
        server_response = self.client.recv(1024)
        print(server_response.decode())


    def cmd_pwd(self,*args):
        current_path = global_manage.get_value('current_path')
        print(current_path)

    def cmd_cd(self,*args):
        #维护一套路径映射
        base_dir = settings.root_catalog
        try:
            print("cd %s"%args[0].split()[1])
            addr = args[0].split()[1]
            if addr.startswith("/"):
                #绝对路径
                username = global_manage.get_value('username')
                current_path = settings.root_catalog + '/' + username
                if addr.startswith(current_path) and len(current_path) <= len(addr):
                    msg = {"addr":addr,"action":"cd"}
                    self.client.send(json.dumps(msg).encode())
                    cd_result = self.client.recv(1024)
                    if eval(cd_result.decode())["cd_result"] == "success":
                        current_path = addr
                        global_manage.set_value('current_path', addr)
                        print("cd %s success"%eval(cd_result.decode())["catalog"])



                else:
                    print("error occurd")

            elif addr.startswith("."):
                count = addr.count(".")
                pass
            else:
                addr = global_manage.get_value('current_path')+'/' + addr
                msg = {"addr": addr, "action": "cd"}

                self.client.send(json.dumps(msg).encode())
                cd_result = self.client.recv(1024)

                if eval(cd_result.decode())["cd_result"] == "error":
                    print("no such dir")
                else:
                    global_manage.set_value('current_path', addr)
                    print("cd %s" % addr)





        except IndexError:
            username = global_manage.get_value('username')
            print("username",username)
            current_path = settings.root_catalog + '/' + username
            global_manage.set_value('current_path', current_path)
            print("cd %s" % current_path)




    def process_view(self,transferred, toBeTransferred):
        print("进度条")
        bar_len = 60
        filled_len = int(round(bar_len * transferred / float(toBeTransferred)))
        percents = round(100.0 * transferred / float(toBeTransferred), 1)
        bar = '=' * filled_len + '-' * (bar_len - filled_len)
        sys.stdout.write('[%s] %s%s ...\r' % (bar, percents, '%'))
        sys.stdout.flush()
if __name__ == "__main__":
    client = FTP_CLIENT()
    client.connect("localhost",10003)
    client.interactive()
